﻿public class McpAuthenticationMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IConfiguration _configuration;
    private readonly ILogger<McpAuthenticationMiddleware> _logger;

    public McpAuthenticationMiddleware(
        RequestDelegate next,
        IConfiguration configuration,
        ILogger<McpAuthenticationMiddleware> logger)
    {
        _next = next;
        _configuration = configuration;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 只对 MCP 端点进行认证
        if (!context.Request.Path.StartsWithSegments("/mcp"))
        {
            await _next(context);
            return;
        }

        // 检查是否启用认证
        var authEnabled = _configuration.GetValue<bool>("McpAuth:Enabled");
        if (!authEnabled)
        {
            await _next(context);
            return;
        }

        // 验证是否有 Token
        var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
        if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsJsonAsync(new { error = "Unauthorized" });
            return;
        }

        // 验证 Token 是否有效
        var token = authHeader.Substring("Bearer ".Length).Trim();
        var validTokens = _configuration.GetSection("McpAuth:ValidTokens").Get<string[]>();
        if (validTokens == null || !validTokens.Contains(token))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsJsonAsync(new { error = "Invalid token" });
            return;
        }

        await _next(context);
    }
}